import axios from 'axios';
import base from './baseUrl'
// 获取token
import { thisPinia } from '@/pinia/index';
// 请求loading
import { ElLoading, ElMessage } from 'element-plus'
// 跳转路由
import router from '@/router'
// 格式化参数
import qs from 'qs'

// Axios实例
const service = axios.create({
  baseURL: base.baseUrl,
  timeout: 100000,
});

let ifQuit = false

let loading = null
let ifLoading = true
const options = {
  lock: true,
  text: '加载中...',
  background: 'rgba(0, 0, 0, 0.3)'
}

const resetLoading = () => {
  if (loading) {
    ifLoading = true
    loading.close()
    loading = null
  }
}
// 请求拦截
service.interceptors.request.use(
  async (config) => {
    if (ifLoading) { loading = ElLoading.service(options) }
    const { token } = thisPinia()
    if (token) { config.headers['Authorization'] = token }
    // if (config.method == '*' && config.xxx == '*') { } // 拦截处理
    return config;
  },
  error => {
    resetLoading()
    return Promise.reject(error);
  }
);

// 响应拦截
service.interceptors.response.use(
  response => {
    resetLoading()
    const { responseType } = response.request
    if (responseType === 'blob') {
      return response
    } else {
      const { code, message, msg } = response.data
      switch (code) {
        case 200:
          ifQuit = false
          return response.data;
        default:
          ElMessage({
            message: message || msg || '网络异常',
            type: 'error',
            plain: true,
          })
          return Promise.reject('接口报错了！找后端！')
      }
    }
  },
  error => {
    resetLoading()
    if (error.response) {
      switch (error.response.status) {
        case 404:
          console.error('请求的资源不存在');
          break;
        case 401:
          if (!ifQuit) {
            ElMessage({
              message: '登录状态已过期',
              type: 'error',
              plain: true,
            })
            // store.commit('saveToken', '')
            router.push('/login')
            ifQuit = true
          }
          return Promise.reject('登录状态已过期');
        default:
          console.error('请求失败', error.response.data);
      }
    } else if (error.request) {
      console.error('请求超时或网络错误', error.request);
    } else {
      console.error('请求配置错误', error.message);
    }
    return Promise.reject(error.response);
  }
);


export default {
  get(url, params) {
    return service({
      method: 'get', url, params,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  post(url, data) {
    return service({
      method: 'post', url, data,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  put(url, data) {
    return service({
      method: 'put', url, data,
      headers: {
        'Content-Type': 'application/json',
      }
    })
  },
  delete(url, params) {
    return service({
      method: 'delete', url, params,
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      }
    })
  },
  getBlob(url, params) {
    return service({
      method: 'get', url, params,
      responseType: 'blob',
      timeout: 0,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    })
  },
  postBlob(url, data) {
    return service({
      method: 'post', url, data,
      responseType: 'blob',
      timeout: 0,
      headers: {
        'Content-Type': 'application/json'
      }
    })
  },
  postFormData(url, data) {
    return service({
      method: 'post', url, data,
      ContentType: 'multipart/form-data'
    })
  },
  postParamsConversion(url, data) {
    return service({
      method: 'post',
      url: `${url}?${qs.stringify(data)}`
    })
  }
}
